package com.qili.util;

import com.qili.exception.MyException;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

import static java.util.Objects.isNull;


/**
 * Created by meng on 2018/5/8.
 * 文件上传工具类
 */
@Getter
@Setter
@ConfigurationProperties(value = "supervisor")
@Component
public class UploadUtil {

    /**
     * 按照当日创建文件夹
     */
    @Value("${supervisor.isDayType}")
    private boolean isDayType;
    /**
     * 自定义文件路径
     */
    @Value("${supervisor.uploadPath}")
    private String uploadPath;

    /**
     * 临时文件路径
     */
    @Value("${supervisor.tempPath}")
    private String tempPath;

    /**
     * 默认文件路径
     */
    @Value("${supervisor.batchPath}")
    private String batchPath;
    /**
     * 合同文件路径
     */
    @Value("${supervisor.zbhtPath}")
    private String zbhtPath;
    /**
     * 用户文件路径
     */
    @Value("${supervisor.personPath}")
    private String personPath;

    /**
     * 用户文件路径
     */
    @Value("${supervisor.userPath}")
    private String userPath;

    /**
     * 正中用户目录名称
     */
    @Value("${supervisor.userZzPath}")
    private String userZzPath;

    /**
     * 监理系统注册用户--个人目录名称
     */
    @Value("${supervisor.userRegistPersonPath}")
    private String userRegistPersonPath;

    /**
     * 监理系统注册用户--组织目录名称
     */
    @Value("${supervisor.userRegistCompanyPath}")
    private String userRegistCompanyPath;


    @Value("${supervisor.imagePath}")
    private String imagePath;

    @Value("${supervisor.filesuffix}")
    public String file_suffix;


    public UploadUtil() {
    }

    /**
     * @param multipartFile
     * @param uploadType
     * @Author:zhaoyongke
     * @Description:
     * @Date:11:33 2020/11/6
     */
    public LoadType upload(MultipartFile multipartFile, UploadType uploadType) throws IOException {
        if (isNull(multipartFile)) {
            throw new MyException("上传数据/地址获取异常");
        }
        LoadType loadType = fileNameStyle(multipartFile, uploadType);
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), loadType.getCurrentFile());
        return loadType;
    }

    /**
     * @param multipartFile
     * @param psUplaodType
     * @Author:Zhangshuo
     * @Description:
     * @Date:11:33 2020/11/6
     */
    public LoadType upload(MultipartFile multipartFile, String psUplaodType) {
        if (isNull(multipartFile)) {
            throw new MyException("上传数据/地址获取异常");
        }
        UploadType uploadType = UploadType.getEnumByType(Integer.valueOf(psUplaodType));
        LoadType loadType = fileNameStyle(multipartFile, uploadType);
        try {
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), loadType.getCurrentFile());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return loadType;
    }

    /**
     * @param multipartFile
     * @param psUplaodType
     * @param psFilePathId
     * @Author:Zhangshuo
     * @Description:根据文件路径类型存储文件
     * @Date:21:37 2020/11/17
     */
    public LoadType upload(MultipartFile multipartFile, String psUplaodType, String psFilePathId) throws IOException {
        if (isNull(multipartFile)) {
            throw new MyException("上传数据/地址获取异常");
        }
        UploadType uploadType = UploadType.getEnumByType(Integer.valueOf(psUplaodType));
        uploadType.setFilePathId(psFilePathId);
        LoadType loadType = fileNameStyle(multipartFile, uploadType);
        FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), loadType.getCurrentFile());

        return loadType;
    }

    /**
     * @param multipartFile
     * @param uploadType
     * @Author:Zhangshuo
     * @Description:格式化文件名
     * @Date:15:08 2020/11/17
     */
    public LoadType fileNameStyle(MultipartFile multipartFile, UploadType uploadType) {
        //上传原始文件名称
        String AsOrgFileName = multipartFile.getOriginalFilename();
        //准备文件LoadType
        LoadType loadType = prepareFileLoadType(AsOrgFileName, uploadType);
        //根据类型存储文件
        String AsPath = getFilepath(uploadType);
        int suffixLen = loadType.getFileName().lastIndexOf(".");
        String  filename="";
        if(-1!=suffixLen){
            // 将后缀名转成小写后存储 20220613
             filename=loadType.getFileName().substring(0,suffixLen)+loadType.getSuffix();
        }else{
            // 20221007 解决 咨询付款申请 上传图片报错
            filename= loadType.getFileName();
        }

        //获取文件路径
        loadType.setCurrentFile(new File(AsPath + "/" + filename));
        return loadType;
    }

    /**
     * @param uploadType
     * @Author:Zhangshuo
     * @Description:根据文件类型获取文件路径
     * @Date:13:40 2020/11/17
     */
    private String getFilepath(UploadType uploadType) {
        //文件主路径
        String AsMainPath = uploadPath;
        //文件子路径
        String AsSubPath = "";
        //根据类型存储文件
        switch (uploadType) {
            case CUSTOM:
                AsSubPath = FilePathUtil.getSavePathByFileType(uploadType);
                break;
            case PERSON:
                AsSubPath = personPath;
                break;
            case ArtImage:
                AsSubPath = imagePath;
                break;
            default:
                AsSubPath = batchPath;
                break;
        }
        String AsPath = AsMainPath + AsSubPath;
        AsPath = FilePathUtil.doFileSeparator(AsPath);
        File AfTmp = new File(AsPath);
        if (!AfTmp.exists()) {
            AfTmp.mkdirs();
        }
        return AsPath;
    }
     /**
     * @Author:zhaoyongke
     * @Description: 判断文件是否存在
     * @param uploadType
     * @Date:19:11 2021/2/3
     */
    public  Boolean isExistFilepath(UploadType uploadType) {
        Boolean isExist=false;
        //文件主路径
        String AsMainPath = uploadPath;
        //文件子路径
        String AsSubPath = "";
        //根据类型存储文件
        switch (uploadType) {
            case CUSTOM:
                AsSubPath = FilePathUtil.getSavePathByFileType(uploadType);
                break;
            case PERSON:
                AsSubPath = personPath;
                break;
            case ArtImage:
                AsSubPath = imagePath;
                break;
            default:
                AsSubPath = batchPath;
                break;
        }
        String AsPath = AsMainPath + AsSubPath;
        AsPath = FilePathUtil.doFileSeparator(AsPath);
        File AfTmp = new File(AsPath);
        if (AfTmp.exists()) {
            isExist=true;
        }
        return isExist;
    }


    /**
     * @param
     * @Author:Zhangshuo
     * @Description:是否允许文件类型
     * @Date:14:11 2020/11/17
     */
    private Boolean whehterAllowFileType(String psFileSuffix) {
        String  fileSuffix=psFileSuffix.replace(".", "");
        String[] split = file_suffix.split(",");
        boolean contains = Arrays.asList(split).contains(fileSuffix);
        return contains;
//        int i = Arrays.binarySearch(file_suffix.split(","), kk);
//        return Arrays.binarySearch(file_suffix.split(","), kk) >= 0;
    }

    /**
     * @param
     * @Author:Zhangshuo
     * @Description:是否允许文件类型
     * @Date:14:11 2020/11/17
     */
    public Boolean whehterAllowFileType(MultipartFile file) {
        String fullFileName = file.getOriginalFilename();
        String fileSuffixName = fullFileName.substring(fullFileName.lastIndexOf(".")+1);
        return Arrays.binarySearch(file_suffix.split(","), fileSuffixName) >= 0;
    }

    /**
     * @param psOrgFileName
     * @Author:Zhangshuo
     * @Description:准备文件
     * @Date: 2020/11/17
     */
    private LoadType prepareFileLoadType(String psOrgFileName, UploadType uploadType) {
        //文件名称
        String AsOrgFileName = psOrgFileName;
        //提交文件名称
        String AsPostFileName = uploadType.getFileName();
        //保存的文件名称
        String AsSaveFileName = "";

        LoadType loadType = new LoadType();
        loadType.setOriginalFileName(AsOrgFileName);

        int suffixLen = AsOrgFileName.lastIndexOf(".");
        //文件后缀名
        String AsSuffix = "";
        if ("blob".equals(AsOrgFileName)) {
            AsOrgFileName = UUID.randomUUID() + ".png";
        } else if (suffixLen == -1) {
            throw new MyException("文件获取异常");
        }

        //带.的后缀名
        AsSuffix = AsOrgFileName.substring(suffixLen, AsOrgFileName.length()).toLowerCase();
        //是否允许上传的文件类型
        if (!whehterAllowFileType(AsSuffix)) {
            throw new MyException("抱歉，上传文件不是允许的文件类型！！");
        }

        //获取文件名称
        if (StringUtil.isBlank(AsPostFileName)) {
            //获取没有后缀的文件名
            AsSaveFileName = AsOrgFileName.replace(AsSuffix, "");
            //最终的文件名称
            AsSaveFileName = new Date().getTime() + "_" + UUID.randomUUID() + AsSuffix;
        } else {
            AsSaveFileName = AsPostFileName;
        }
        loadType.setFileName(AsSaveFileName);

        loadType.setSuffix(AsSuffix);
        return loadType;
    }

    public String styleFileName(String fileName, String originalFilename) {
        if(StringUtils.isBlank(fileName) || StringUtils.isBlank(originalFilename)){
            return "";
        }
        if(originalFilename.lastIndexOf(".") == -1){
            return "";
        }
        //带.的后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //是否允许上传的文件类型
        if (!whehterAllowFileType(suffix)) {
            throw new MyException("抱歉，上传文件不是允许的文件类型！！");
        }
        return fileName + originalFilename.substring(originalFilename.indexOf("."));
    }


    public String getUserFileName(String fileType){
        String fileName = "";
        switch (fileType){
            case "201":
                fileName = "营业执照";
                break;
            case "202":
                fileName = "电子签章";
                break;
            case "203":
                fileName = "电子签名";
                break;
            case "204":
                fileName = "身份证正面";
                break;
            case "205":
                fileName = "身份证反面";
                break;
            case "206":
                fileName = "学历证明";
                break;
            case "207":
                fileName = "资历证明";
                break;
            case "208":
                fileName = "头像";
                break;
            case "551":
                fileName = "资质证明";
                break;
            case "552":
                fileName = "承诺函";
                break;
            case "555":
                fileName = "第一学历证明";
                break;
            case "556":
                fileName = "第一学历学信网";
                break;
            case "557":
                fileName = "最终学历证明";
                break;
            case "558":
                fileName = "最终学历学信网";
                break;
            case "0819":
                fileName = "封面";
                break;
        }
        return fileName;
    }

    public String getFileCountByFileName(String fileNameFront,String filePath) {
        System.out.println(fileNameFront);
        System.out.println(filePath);
        File fileDic = new File(filePath);
        if(fileDic.exists() && fileDic.isDirectory()){
            //获取文件夹下面的所有文件
            File[] files = fileDic.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.isFile();
                }
            });
            int fileCountOfType = 0;
            for(File file : files){
                if(file.getName().startsWith(fileNameFront+"_")){
                    fileCountOfType++;
                }
            }
            return fileNameFront+"_"+fileCountOfType;
        }
        return fileNameFront;
    }
}


